import { QueueInfos, JobsConfig, OnStartQueueConfig, QueueConfig, QueueInfo, FromQueueConfig } from '../types/index';
import Job from '../job/Job'
import JobStatus from '../job/JobStatus';
import Queue from '../queue/Queue';
import { jobManager } from './index';
import * as fs from 'fs-extra'
import browser from 'src/utils/browser';

export default class QueueManager {

  private cachePath: string // 运行状态持久化文件路径

  private queues: Map<string, Queue> 

  private successJobsSize: number = 0

  private failJobsSize: number = 0

  private running: number = 0

  private pause: boolean = false // 是否暂停派发任务

  addOnStartConfig (config: OnStartQueueConfig) {
    let queueName = this.checkQueue(null, config)
    let url: string[] = config.url.constructor === Array ? config.url as string[] : [config.url as string]
    this.addToQueue({
      queueName,
      urls: url
    })
  }

  checkQueue (queueName: string, config: QueueConfig): string {
    queueName = queueName ? queueName : config['type'] + '_' + config['target'].constructor.name + '_' + config['method']
    config['name'] = queueName
    if (this.queues[queueName]) {
      this.queues[queueName] = new Queue(config as FromQueueConfig)
    }
    return queueName
  }

  addToQueue (config: JobsConfig) {
    let queue: Queue = this.queues[config.queueName]
    config.urls.forEach(url => {
      let job: Job = new Job(url)
      job.setQueueName(config.queueName)
      job.setTryNum(3)
      job.setStatus(JobStatus.Created)
      queue.push(job)
      jobManager.save(job)
    })
  }

  saveToCache () {
    try {
      const data = JSON.stringify(this, (key, value) => {
        if (['cachePath', 'pause'].indexOf(key) > -1) {
          return undefined
        }
        return value
      })
      fs.writeFileSync(this.cachePath, data)
      return true
    } catch (err) {
      console.error(err)
      return false
    }
  }

  loadFromCache (cachePath: string) {
    this.cachePath = cachePath
    if (fs.existsSync(cachePath)) {
      const data = JSON.parse(fs.readFileSync(cachePath, 'utf-8'))
      const tmpQueueManager = data as QueueManager
      this.successJobsSize = tmpQueueManager.successJobsSize
      this.running = tmpQueueManager.running
      this.failJobsSize = tmpQueueManager.failJobsSize
      // TODO 序列化queues
      // this.queueInfos = tmpQueueManager.queueInfos as QueueInfos
    }
    // TODO 向页面推送展示信息
  }

  resetPause (pause: boolean) {
    this.pause = pause
    // TODO 向页面推送展示信息
  }

  async startTasks () {
    
  }
}